// SPDX-FileCopyrightText: 2025 UnionTech Software Technology Co., Ltd.
// SPDX-License-Identifier: MIT

package logger

import (
	"io"
	"os"
	"path/filepath"
	"time"

	"github.com/sirupsen/logrus"
)

// Logger 统一日志接口
type Logger interface {
	// 基础日志方法
	Info(args ...interface{})
	Infof(format string, args ...interface{})
	Warn(args ...interface{})
	Warnf(format string, args ...interface{})
	Error(args ...interface{})
	Errorf(format string, args ...interface{})
	Debug(args ...interface{})
	Debugf(format string, args ...interface{})
	Fatal(args ...interface{})
	Fatalf(format string, args ...interface{})

	// 结构化日志方法
	WithField(key string, value interface{}) Logger
	WithFields(fields map[string]interface{}) Logger
	WithError(err error) Logger

	// 配置方法
	SetLevel(level string) error
	SetOutput(output io.Writer)
	SetFormatter(formatter logrus.Formatter)
}

// LogrusLogger 基于 logrus 的日志实现
type LogrusLogger struct {
	*logrus.Logger
}

// LogrusEntry 基于 logrus.Entry 的日志条目
type LogrusEntry struct {
	*logrus.Entry
}

// 全局默认日志器
var DefaultLogger Logger

func init() {
	DefaultLogger = New()
}

// New 创建新的日志器
func New() Logger {
	logger := logrus.New()

	// 设置默认格式
	logger.SetFormatter(&logrus.TextFormatter{
		TimestampFormat: time.RFC3339,
		FullTimestamp:   true,
		ForceColors:     true,
	})

	// 设置默认级别
	logger.SetLevel(logrus.InfoLevel)

	// 设置默认输出
	logger.SetOutput(os.Stdout)

	return &LogrusLogger{Logger: logger}
}

// NewWithConfig 根据配置创建日志器
func NewWithConfig(level string, output io.Writer, format string) (Logger, error) {
	logger := logrus.New()

	// 设置日志级别
	if level != "" {
		logLevel, err := logrus.ParseLevel(level)
		if err != nil {
			return nil, err
		}
		logger.SetLevel(logLevel)
	}

	// 设置输出
	if output != nil {
		logger.SetOutput(output)
	}

	// 设置格式
	switch format {
	case "json":
		logger.SetFormatter(&logrus.JSONFormatter{
			TimestampFormat: time.RFC3339,
		})
	case "text":
		logger.SetFormatter(&logrus.TextFormatter{
			TimestampFormat: time.RFC3339,
			FullTimestamp:   true,
		})
	default:
		logger.SetFormatter(&logrus.TextFormatter{
			TimestampFormat: time.RFC3339,
			FullTimestamp:   true,
			ForceColors:     true,
		})
	}

	return &LogrusLogger{Logger: logger}, nil
}

// NewWithFile 创建带文件输出的日志器
func NewWithFile(filename string, level string) (Logger, error) {
	// 确保目录存在
	dir := filepath.Dir(filename)
	if err := os.MkdirAll(dir, 0755); err != nil {
		return nil, err
	}

	file, err := os.OpenFile(filename, os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0644)
	if err != nil {
		return nil, err
	}

	return NewWithConfig(level, file, "text")
}

// NewWithFileAndConsole 创建同时输出到文件和控制台的日志器
func NewWithFileAndConsole(filename string, level string) (Logger, error) {
	// 确保目录存在
	dir := filepath.Dir(filename)
	if err := os.MkdirAll(dir, 0755); err != nil {
		return nil, err
	}

	file, err := os.OpenFile(filename, os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0644)
	if err != nil {
		return nil, err
	}

	// 同时输出到文件和控制台
	multiWriter := io.MultiWriter(os.Stdout, file)

	return NewWithConfig(level, multiWriter, "text")
}

// LogrusLogger 方法实现

func (l *LogrusLogger) Info(args ...interface{}) {
	l.Logger.Info(args...)
}

func (l *LogrusLogger) Infof(format string, args ...interface{}) {
	l.Logger.Infof(format, args...)
}

func (l *LogrusLogger) Warn(args ...interface{}) {
	l.Logger.Warn(args...)
}

func (l *LogrusLogger) Warnf(format string, args ...interface{}) {
	l.Logger.Warnf(format, args...)
}

func (l *LogrusLogger) Error(args ...interface{}) {
	l.Logger.Error(args...)
}

func (l *LogrusLogger) Errorf(format string, args ...interface{}) {
	l.Logger.Errorf(format, args...)
}

func (l *LogrusLogger) Debug(args ...interface{}) {
	l.Logger.Debug(args...)
}

func (l *LogrusLogger) Debugf(format string, args ...interface{}) {
	l.Logger.Debugf(format, args...)
}

func (l *LogrusLogger) Fatal(args ...interface{}) {
	l.Logger.Fatal(args...)
}

func (l *LogrusLogger) Fatalf(format string, args ...interface{}) {
	l.Logger.Fatalf(format, args...)
}

func (l *LogrusLogger) WithField(key string, value interface{}) Logger {
	return &LogrusEntry{Entry: l.Logger.WithField(key, value)}
}

func (l *LogrusLogger) WithFields(fields map[string]interface{}) Logger {
	return &LogrusEntry{Entry: l.Logger.WithFields(fields)}
}

func (l *LogrusLogger) WithError(err error) Logger {
	return &LogrusEntry{Entry: l.Logger.WithError(err)}
}

func (l *LogrusLogger) SetLevel(level string) error {
	logLevel, err := logrus.ParseLevel(level)
	if err != nil {
		return err
	}
	l.Logger.SetLevel(logLevel)
	return nil
}

func (l *LogrusLogger) SetOutput(output io.Writer) {
	l.Logger.SetOutput(output)
}

func (l *LogrusLogger) SetFormatter(formatter logrus.Formatter) {
	l.Logger.SetFormatter(formatter)
}

// LogrusEntry 方法实现

func (e *LogrusEntry) Info(args ...interface{}) {
	e.Entry.Info(args...)
}

func (e *LogrusEntry) Infof(format string, args ...interface{}) {
	e.Entry.Infof(format, args...)
}

func (e *LogrusEntry) Warn(args ...interface{}) {
	e.Entry.Warn(args...)
}

func (e *LogrusEntry) Warnf(format string, args ...interface{}) {
	e.Entry.Warnf(format, args...)
}

func (e *LogrusEntry) Error(args ...interface{}) {
	e.Entry.Error(args...)
}

func (e *LogrusEntry) Errorf(format string, args ...interface{}) {
	e.Entry.Errorf(format, args...)
}

func (e *LogrusEntry) Debug(args ...interface{}) {
	e.Entry.Debug(args...)
}

func (e *LogrusEntry) Debugf(format string, args ...interface{}) {
	e.Entry.Debugf(format, args...)
}

func (e *LogrusEntry) Fatal(args ...interface{}) {
	e.Entry.Fatal(args...)
}

func (e *LogrusEntry) Fatalf(format string, args ...interface{}) {
	e.Entry.Fatalf(format, args...)
}

func (e *LogrusEntry) WithField(key string, value interface{}) Logger {
	return &LogrusEntry{Entry: e.Entry.WithField(key, value)}
}

func (e *LogrusEntry) WithFields(fields map[string]interface{}) Logger {
	return &LogrusEntry{Entry: e.Entry.WithFields(fields)}
}

func (e *LogrusEntry) WithError(err error) Logger {
	return &LogrusEntry{Entry: e.Entry.WithError(err)}
}

func (e *LogrusEntry) SetLevel(level string) error {
	logLevel, err := logrus.ParseLevel(level)
	if err != nil {
		return err
	}
	e.Entry.Logger.SetLevel(logLevel)
	return nil
}

func (e *LogrusEntry) SetOutput(output io.Writer) {
	e.Entry.Logger.SetOutput(output)
}

func (e *LogrusEntry) SetFormatter(formatter logrus.Formatter) {
	e.Entry.Logger.SetFormatter(formatter)
}

// 便利函数，使用默认日志器

func Info(args ...interface{}) {
	DefaultLogger.Info(args...)
}

func Infof(format string, args ...interface{}) {
	DefaultLogger.Infof(format, args...)
}

func Warn(args ...interface{}) {
	DefaultLogger.Warn(args...)
}

func Warnf(format string, args ...interface{}) {
	DefaultLogger.Warnf(format, args...)
}

func Error(args ...interface{}) {
	DefaultLogger.Error(args...)
}

func Errorf(format string, args ...interface{}) {
	DefaultLogger.Errorf(format, args...)
}

func Debug(args ...interface{}) {
	DefaultLogger.Debug(args...)
}

func Debugf(format string, args ...interface{}) {
	DefaultLogger.Debugf(format, args...)
}

func Fatal(args ...interface{}) {
	DefaultLogger.Fatal(args...)
}

func Fatalf(format string, args ...interface{}) {
	DefaultLogger.Fatalf(format, args...)
}

func WithField(key string, value interface{}) Logger {
	return DefaultLogger.WithField(key, value)
}

func WithFields(fields map[string]interface{}) Logger {
	return DefaultLogger.WithFields(fields)
}

func WithError(err error) Logger {
	return DefaultLogger.WithError(err)
}

func SetLevel(level string) error {
	return DefaultLogger.SetLevel(level)
}

func SetOutput(output io.Writer) {
	DefaultLogger.SetOutput(output)
}

func SetFormatter(formatter logrus.Formatter) {
	DefaultLogger.SetFormatter(formatter)
}
